package system

import (
	"project-info/src/handle/response"
	"project-info/src/handle/system/service"

	"project-info/src/lib")

var oidcService = service.NewOIDCService()

type CallbackRequest struct {
	Code        string `json:"code" binding:"required"`
	State       string `json:"state"`
	RedirectURI string `json:"redirect_uri" binding:"required"`
}

type RefreshRequest struct {
	RefreshToken string `json:"refresh_token" binding:"required"`
}

type AuthResponse struct {
	AccessToken  string      `json:"access_token"`
	IDToken      string      `json:"id_token"`
	RefreshToken string      `json:"refresh_token"`
	UserInfo     interface{} `json:"user_info"`
	ExpiresIn    int         `json:"expires_in"`
}

// 处理OIDC回调
func HandleCallback(c *lib.GinContext) error {
	var req CallbackRequest
	if err := c.Bind(&req); err != nil {
		c.Logger().Error(err.Error())
		return response.JsonFail(c, "参数绑定失败")
	}

	// 交换授权码获取令牌
	tokenResp, err := oidcService.ExchangeCodeForTokens(req.Code, req.RedirectURI)
	if err != nil {
		c.Logger().Error(err.Error())
		return response.JsonFail(c, "交换授权码获取令牌失败")
	}

	// 获取用户信息
	userInfo, err := oidcService.GetUserInfo(tokenResp.AccessToken)
	if err != nil {
		c.Logger().Error(err.Error())
		return response.JsonFail(c, "获取用户信息失败")
	}

	r := AuthResponse{
		AccessToken:  tokenResp.AccessToken,
		IDToken:      tokenResp.IDToken,
		RefreshToken: tokenResp.RefreshToken,
		UserInfo:     userInfo,
		ExpiresIn:    tokenResp.ExpiresIn,
	}

	return response.JsonOk(c, r, "登录成功")
}

// 刷新令牌
func RefreshToken(c *lib.GinContext) error {
	var req RefreshRequest
	if err := c.Bind(&req); err != nil {
		c.Logger().Error(err.Error())
		return response.JsonFail(c, "参数绑定失败")
	}

	tokenResp, err := oidcService.RefreshToken(req.RefreshToken)
	if err != nil {
		c.Logger().Error(err.Error())
		return response.JsonFail(c, "刷新令牌失败")
	}

	r := map[string]interface{}{
		"access_token":  tokenResp.AccessToken,
		"id_token":      tokenResp.IDToken,
		"expires_in":    tokenResp.ExpiresIn,
		"refresh_token": tokenResp.RefreshToken,
	}

	return response.JsonOk(c, r, "刷新令牌成功")
}

// 获取当前用户信息
func GetCurrentUser(c *lib.GinContext) error {
	// 从中间件获取用户信息
	userInfo, _ := c.Get("user")
	if userInfo == nil {
		c.Logger().Error("User not authenticated")
		return response.JsonFail(c, "用户未认证")
	}

	return response.JsonOk(c, userInfo, "获取用户信息成功")
}
